from flask import (
    Blueprint,
    request,
    g,
    render_template,
)

from exit import db
from .decorators import login_need
from flask_paginate import Pagination, get_page_parameter
from .models import CMSRecord
from utils import restful, common_util, api_util
from datetime import datetime, date
# from apps.api.forms import TradeIdForm
from apps.api.models import *
from apps.common.models import *
from decimal import Decimal
from sqlalchemy import or_
from .views_cms import bp
import json


@bp.route('/test/')
def task_test():
    return '测试'


@bp.route('/orders/cms_withdraw_orders/')  # 后台提现订单
@login_need
def cms_withdraw_orders():
    user_id = request.args.get('user_id')
    status = request.args.get('status')
    status = int(status)
    # print(user_id)
    if status == 0:
        sql ="select DATE_FORMAT(create_time,'%Y-%m-%d') days,sum(price) prices from c_order_withdraw where status = 0 group by days"
        result = db.session.execute(sql).fetchall()
        price_str = '未审核：'
        for i in result:
            price_str += '{} <{}> '.format(i.days, int(i.prices))
        return render_template(
            'cms_orders/withdraw.html', status=status, user_id=user_id, price_str=price_str
        )
    else:
        return render_template(
            'cms_orders/withdraw_complete.html', status=status, user_id=user_id
        )


@bp.route('/orders/withdraw_info/')  # 提现订单信息
@login_need
def withdraw_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    withdraw_order_list = list()
    username = request.args.get('user_id')
    status = request.args.get('status')
    status = int(status)
    # print(username)
    if status == 0:
        if username:
            withdraw_obj = db.session.query(WithdrawOrder).join(User, WithdrawOrder.user_id == User.id).filter(
                or_(User.username == username, User.phone == username),
                WithdrawOrder.status == status
            ).order_by(WithdrawOrder.create_time)
        else:
            withdraw_obj = WithdrawOrder.query.filter_by(status=status).order_by(WithdrawOrder.create_time)
    else:
        if username:
            withdraw_obj = db.session.query(WithdrawOrder).join(User, WithdrawOrder.user_id == User.id).filter(
                or_(User.username == username, User.phone == username),
                WithdrawOrder.status != 0
            ).order_by(WithdrawOrder.update_time.desc())
        else:
            withdraw_obj = WithdrawOrder.query.filter(WithdrawOrder.status != 0).order_by(
                WithdrawOrder.update_time.desc())

    total = withdraw_obj.count()
    withdraw_order = withdraw_obj.slice(start, end)
    for i in withdraw_order:
        withdraw_order_json = i.withdraw_json()
        user = User.query.filter_by(id=i.user_id).first()
        # if i.w_type == 1:
        #     withdraw_order_json['w_type'] = '余额'
        # elif i.w_type == 2:
        #     withdraw_order_json['w_type'] = '奖金币'
        # else:
        #     withdraw_order_json['w_type'] = '扫码支付'
        if i.status == 0:
            status = '审核中'
        elif i.status == 1:
            status = '成功'
        elif i.status == 2:
            status = '失败'
        withdraw_order_json['status'] = status
        withdraw_order_json['order_id'] = i.id
        withdraw_order_json['trade_no'] = i.trade_no
        withdraw_order_json['price'] = i.price * Decimal('1')
        withdraw_order_json['username'] = user.username
        withdraw_order_json['nickname'] = user.nickname
        withdraw_order_json['real_name'] = user.real_name
        withdraw_order_json['user_id'] = user.id
        withdraw_order_json['phone'] = user.phone

        pay_account = UserPayAccount.query.filter_by(user_id=i.user_id, pay_type=i.pay_type).first()
        if pay_account:
            withdraw_order_json['pay_name'] = pay_account.pay_name
            withdraw_order_json['pay_real_name'] = pay_account.real_name
            withdraw_order_json['pay_card'] = pay_account.pay_card
            withdraw_order_json['pay_img'] = pay_account.pay_img
        withdraw_order_list.append(withdraw_order_json)
    return restful.table_success(data=withdraw_order_list, count=total)


@bp.route('/reset_annotate/', methods=['POST'])  # 修改注释
@login_need
def reset_annotate():
    annotate = request.form.get('annotate')
    user_id = request.form.get('user_id')
    if annotate is None or annotate == '':
        return restful.params_error(message='请填写注释')
    user = User.query.filter_by(id=user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    if user.annotate != annotate:
        record = '用户注释<{}>--修改为<{}>'.format(user.annotate or '无', annotate)
        # 后台记录
        cms_record = CMSRecord(
            cms_id=g.cms_user.id,
            ip=request.remote_addr,
            record=record,
            user_id=user.id,
        )
        db.session.add(cms_record)

        user.annotate = annotate
        db.session.commit()
    return restful.success()


# 提现完成订单按钮
@bp.route('/orders/withdraw_order_success/', methods=['POST'])
@login_need
def withdraw_order_success():
    order_id = request.form.get('order_id')
    # print(order_id)
    withdraw_order = WithdrawOrder.query.filter_by(id=order_id, status=0).with_for_update().first()
    if not withdraw_order:
        return restful.params_error(message='未找到订单, 或订单已改变状态!')
    now = datetime.now()
    user = User.query.filter_by(id=withdraw_order.user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')

    withdraw_order.status = 1
    withdraw_order.update_time = now
    # withdraw_order.admin_id = g.cms_user.id

    record = '完成提现订单'
    # 后台记录
    cms_record = CMSRecord(
        cms_id=g.cms_user.id,
        ip=request.remote_addr,
        record=record,
        user_id=user.id,
    )
    db.session.add(cms_record)
    db.session.commit()
    # msg = '【】提现订单状态发生改变，请登陆查看。'
    # sms.send_sms_message(user.phone, msg)
    return restful.success()


@bp.route('/orders/withdraw_order_cancel/', methods=['POST'])  # 取消提现订单
@login_need
def withdraw_order_cancel():
    order_id = request.form.get('order_id')
    # print(order_id)
    withdraw_order = WithdrawOrder.query.filter_by(id=order_id, status=0).with_for_update().first()
    if not withdraw_order:
        return restful.params_error(message='未找到订单, 或订单已改变状态!')
    now = datetime.now()
    user = User.query.filter_by(id=withdraw_order.user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')

    withdraw_order.status = 2
    withdraw_order.update_time = now
    # if withdraw_order.w_type == 1:
    user.income += withdraw_order.income
    # user.income_r -= withdraw_order.price * Decimal('0.2')
    # if user.income_r < 0:
    #     user.income_r = 0

    api_util.user_record(user_id=user.id, r_label=7, r_type=2, r_state=1, num=withdraw_order.income,
                         r_wallet=1, status=1)
    record = '失败提现订单'
    # 后台记录
    cms_record = CMSRecord(
        cms_id=g.cms_user.id,
        ip=request.remote_addr,
        record=record,
        user_id=user.id,
    )
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


# 批量完成提现
@bp.route('/orders/withdraw_batch/', methods=['POST'])
@login_need
def withdraw_batch():
    order_list = request.get_data()
    order_list = json.loads(order_list)
    # print(order_list)

    for i in order_list:
        withdraw_order = WithdrawOrder.query.filter_by(id=i['id'], status=0).with_for_update().first()
        if not withdraw_order:
            # return restful.params_error(message='未找到订单, 或订单已改变状态!')
            continue
        now = datetime.now()
        user = User.query.filter_by(id=withdraw_order.user_id).first()
        if user is None:
            # return restful.params_error(message='未找到用户')
            continue
        withdraw_order.status = 1
        withdraw_order.update_time = now
        # withdraw_order.admin_id = g.cms_user.id

        record = '完成提现订单'
        # 后台记录
        cms_record = CMSRecord(
            cms_id=g.cms_user.id,
            ip=request.remote_addr,
            record=record,
            user_id=user.id,
        )
        db.session.add(cms_record)
    db.session.commit()
    # msg = '【】提现订单状态发生改变，请登陆查看。'
    # sms.send_sms_message(user.phone, msg)
    return restful.success()


# 批量取消提现
@bp.route('/orders/withdraw_batch_cancel/', methods=['POST'])  # 批量取消提现
@login_need
def withdraw_batch_cancel():
    order_list = request.get_data()
    order_list = json.loads(order_list)
    # print(order_list)
    for i in order_list:
        withdraw_order = WithdrawOrder.query.filter_by(id=i['id'], status=0).with_for_update().first()
        if not withdraw_order:
            continue
            # return restful.params_error(message='未找到订单, 或订单已改变状态!')
        now = datetime.now()
        user = User.query.filter_by(id=withdraw_order.user_id).first()
        if user is None:
            continue
            # return restful.params_error(message='未找到用户')

        withdraw_order.status = 2
        withdraw_order.update_time = now
        user.income += withdraw_order.income
        api_util.user_record(user_id=user.id, r_label=7, r_type=2, r_state=1, num=withdraw_order.income,
                             r_wallet=1, status=0)

        # user.income_r -= withdraw_order.price * Decimal('0.2')
        # if user.income_r < 0:
        #     user.income_r = 0
        record = '失败提现订单'
        # 后台记录
        cms_record = CMSRecord(
            cms_id=g.cms_user.id,
            ip=request.remote_addr,
            record=record,
            user_id=user.id,
        )
        db.session.add(cms_record)
    db.session.commit()
    return restful.success()


# 批量提现转换
@bp.route('/orders/withdraw_to_income/', methods=['POST'])  # 批量提现转换
@login_need
def withdraw_to_income():
    return restful.success()


@bp.route('/orders/cms_recharge_orders/')  # 充值订单
@login_need
def cms_recharge_orders():
    status = request.args.get('status')
    user_id = request.args.get('user_id')
    trade_no = request.args.get('trade_no')
    w_type = request.args.get('w_type')
    status = int(status)
    if status == 0:
        return render_template('cms_orders/recharge.html', user_id=user_id, trade_no=trade_no, status=status, w_type=w_type)
    else:
        return render_template('cms_orders/recharge_complete.html', user_id=user_id, trade_no=trade_no, status=status)


@bp.route('/orders/recharge_orders_info/')  # 充值订单信息
@login_need
def recharge_orders_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    recharge_order_list = list()
    user_id = request.args.get('user_id')
    status = request.args.get('status')
    w_type = request.args.get('w_type')
    trade_no = request.args.get('trade_no')
    status = int(status)
    if status == 0:
        filters = list()
        filters.append(RechargeOrder.status == status)
        filters.append(RechargeOrder.order_img.isnot(None))
        if w_type:
            filters.append(RechargeOrder.w_type == w_type)
        else:
            filters.append(RechargeOrder.w_type != 0)
        if trade_no:
            filters.append(RechargeOrder.trade_no.like("%" + str(trade_no) + "%"),)

        # 手机号或者用户名多表查询
        if user_id:
            filters.append(or_(User.phone == user_id, User.username == user_id))
            buy_obj = db.session.query(RechargeOrder).join(
                User, RechargeOrder.user_id == User.id
            ).filter(*filters).order_by(RechargeOrder.create_time)
        else:
            buy_obj = RechargeOrder.query.filter(*filters).order_by(RechargeOrder.create_time)

    else:
        if trade_no:
            buy_obj = RechargeOrder.query.filter(
                RechargeOrder.trade_no.like("%" + str(trade_no) + "%"),
                RechargeOrder.status != 0,
            ).order_by(RechargeOrder.update_time.desc())
        elif user_id:
            buy_obj = db.session.query(RechargeOrder).join(User, RechargeOrder.user_id == User.id).filter(
                or_(User.phone == user_id, User.username == user_id),
                RechargeOrder.status != 0,
            ).order_by(RechargeOrder.update_time.desc())
        else:
            buy_obj = RechargeOrder.query.filter(
                RechargeOrder.status != 0,
            ).order_by(RechargeOrder.update_time.desc())
    total = buy_obj.count()
    shipping_order = buy_obj.slice(start, end)

    for i in shipping_order:
        order_json = i.recharge_order_json()
        user = User.query.filter_by(id=i.user_id).first()
        order_json['order_id'] = i.id
        if i.w_type == 0:
            order_json['w_type'] = '余额'
        else:
            order_json['w_type'] = '余额'

        if i.status == 0:
            order_json['status'] = '未审核'
        elif i.status == 1:
            order_json['status'] = '成功'
        elif i.status == 2:
            order_json['status'] = '失败'
        else:
            order_json['status'] = '取消'

        order_json['phone'] = user.phone
        order_json['user_id'] = user.id
        order_json['username'] = user.username
        recharge_order_list.append(order_json)
    return restful.table_success(data=recharge_order_list, count=total)


# 充值完成订单按钮
@bp.route('/orders/recharge_order_success/', methods=['POST'])
@login_need
def recharge_order_success():
    order_id = request.form.get('order_id')
    # print(order_id)
    recharge_order = RechargeOrder.query.filter_by(id=order_id, status=0).with_for_update().first()
    if not recharge_order:
        return restful.params_error(message='未找到订单, 或订单已改变状态!')
    now = datetime.now()
    user = User.query.filter_by(id=recharge_order.user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    recharge_order.status = 1
    recharge_order.update_time = now

    user.income += recharge_order.price
    api_util.user_record(
        user_id=user.id, r_label=6, r_type=1, r_state=1,
        num=recharge_order.price,  r_wallet=1
    )

    record = '成功 充值订单<{}>'.format(recharge_order.trade_no)
    # 后台记录
    cms_record = CMSRecord(
        cms_id=g.cms_user.id,
        ip=request.remote_addr,
        record=record,
        user_id=user.id,
    )
    db.session.add_all([cms_record])
    db.session.commit()
    return restful.success()


@bp.route('/orders/recharge_order_cancel/', methods=['POST'])  # 取消订单
@login_need
def recharge_order_cancel():
    order_id = request.form.get('order_id')
    recharge_order = RechargeOrder.query.filter_by(id=order_id, status=0).with_for_update().first()
    if not recharge_order:
        return restful.params_error(message='未找到订单, 或订单已改变状态!')
    now = datetime.now()
    user = User.query.filter_by(id=recharge_order.user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    recharge_order.status = 2
    recharge_order.update_time = now

    record = '失败 充值订单<{}>'.format(recharge_order.trade_no)
    # 后台记录
    cms_record = CMSRecord(
        cms_id=g.cms_user.id,
        ip=request.remote_addr,
        record=record,
        user_id=user.id,
    )
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()
